package com.example.study.source

import com.google.gson.annotations.SerializedName
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query

/**
 * Created by lijinxi on 2024/2/28
 * @Description:
 */

data class Movie(
    @SerializedName("title") val title: String = "",
    @SerializedName("year") val year: Int = 0,
    @SerializedName("image") val image: Image? = null
)

data class Image(
    @SerializedName("small") val small: String = ""
)


data class Movies(
    @SerializedName("count") val count: Int = 0,
    @SerializedName("start") val start: Int = 0,
    @SerializedName("total") val total: Int = 0,
    @SerializedName("subjects") val subjects: List<Movie>? = null
)

interface MovieApi {
    @GET("movie/in_theaters")
    suspend fun getMovies(@Query("start") since: Int, @Query("count") perPage: Int): Movies?
}


class MovieRepository {
    companion object {
        private const val BASE_URL = "https://api.douban.com/v2/"
        private const val API_KEY =
            "0df993c66c0c636e29ecbb5344252a4a0b2bdeda43b5688921839c8ecb20399b"
        const val PER_PAGE = 10
    }

    private val client = OkHttpClient.Builder().apply {
        addInterceptor { chain ->
            val originalUrl = chain.request().url()
            val url = originalUrl.newBuilder().addQueryParameter("apiKey", API_KEY).build()
            val request = chain.request().newBuilder().url(url).build()
            chain.proceed(request)
        }
    }.build()

    private val api: MovieApi = Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(
        GsonConverterFactory.create()
    ).client(client).build().create(MovieApi::class.java)

    suspend fun getMovies(since: Int): List<Movie>? {
        /*
        return api.getMovies(since, PER_PAGE)?.let {
            if (it.count != PER_PAGE) null else it.subjects
        }*/

        //本地模拟数据
        val list = mutableListOf<Movie>()
        for (i in since + 0..since + PER_PAGE) {
            list.add(
                Movie(
                    title = "title $i",
                    year = i,
                    image = if (i % 2 == 0) Image(small = "https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF") else Image(
                        "https://t7.baidu.com/it/u=4162611394,4275913936&fm=193&f=GIF"
                    )
                )
            )
        }
        return list
    }
}
